import Vue from 'vue'
import VueRouter from 'vue-router'
// 使用路由懒加载
// import login from '../components/Login'
// import home from '../view/Home'

Vue.use(VueRouter)

// 封装router
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}


const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: () => import('@/view/Login') },
  {
    path: '/home', component: () => import('@/view/Home'), redirect: '/welcome',
    children: [
      { path: '/welcome', component: () => import('@/view/Home/Welcome') },
      { path: '/users', component: () => import('@/view/Home/Users') },
      { path: '/roles', component: () => import('@/view/Home/Roles') },
      { path: '/rights', component: () => import('@/view/Home/Rights') },
      { path: '/goods', component: () => import('@/view/Home/Goods') },
      { path: '/params', component: () => import('@/view/Home/Params') },
      { path: '/categories', component: () => import('@/view/Home/Categories') },
      { path: '/orders', component: () => import('@/view/Home/Orders') },
      { path: '/reports', component: () => import('@/view/Home/Reports') },
      { path: '/goods/add', component: () => import('@/view/Home/Goods/addGood.vue') },
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  let token = sessionStorage.getItem('TOKEN')
  // 登录页面一直开放,此时必须没有token
  if (to.path == '/login' && !token) {
    return next()
  }

  // 存在token
  if (token) {
    // 如果去login，需要退出token在重新登录
    if (to.path == '/login') {
      // 删除token重新登录
      if (confirm('是否需要重新登录')) {
        // 弹框是否退出登录----是
        sessionStorage.removeItem('TOKEN')
        return next()
      } else {
        // -----否
        return next(false)
      }
    } else {
      // 如果去其他的路由放行（除了login）
      return next()
    }
  } else {
    // 没有token的时候只能跳转到login组件 
    return next('/login')
  }

})


export default router
